package com.zsl.service;

import com.zsl.mapper.ProductMapper;
import com.zsl.model.Product;
import com.zsl.model.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
/**
 *  RedisTemplate 实现crud
 * */
public class ProductService2 {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate ;

    @Autowired
    private ProductMapper productMapper;

    public Product getSingle(Long productId) {

        Product product=null;

        String key = "product::"+productId;
        if(redisTemplate.hasKey(key)){

             product = (Product) redisTemplate.opsForValue().get(key);

        }else {
            product   = productMapper.findById(productId).get();
            redisTemplate.opsForValue().set(key, product);

        }


        return product;
    }


    public ResponseMessage remove(Long productId) {

        ResponseMessage responseMessage = new ResponseMessage();

        productMapper.deleteById(productId);

        redisTemplate.delete("product::" + productId);

        responseMessage.setSuccess(true);

        return responseMessage;
    }


    public ResponseMessage save(Product product) {

        ResponseMessage responseMessage = new ResponseMessage();

        productMapper.save(product);


        Boolean flag = false;

        flag = product.getProductId() > 0;

        responseMessage.setSuccess(flag);

         redisTemplate.opsForValue().set("product::"+product.getProductId(),product);

        return responseMessage;


    }


}
